package stdio.costa.moca.pdf;

import com.aspose.words.Cell;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.Node;
import com.aspose.words.Row;
import com.aspose.words.Shape;
import com.aspose.words.Table;

public class ReplaceTextWithImageInCellVisitor extends AbstractReplaceTextWithImageVisitor implements TableVisitor {

	public ReplaceTextWithImageInCellVisitor(String text, byte[] image, DocumentBuilder builder) {
		super(text, image, builder);
	}

	@Override
	public void visit(Table table) {
	}

	@Override
	public void visit(Row row) {
	}

	@Override
	public void visit(Cell cell) throws Exception {
		if (cell.getRange().getText().contains(text)) {
			builder.moveTo(findContainer(cell));
			insertImage(cell);
		}
	}

	protected Node findContainer(Cell cell) {
		Node child = cell.getFirstChild();
		while(child != null) {
			if(child.getRange().getText().contains(text)) {
				return child;
			}
			child = child.getNextSibling();
		}
		return null;
	}

	protected void insertImage(Cell cell) throws Exception {
		cell.getRange().replace(text, "", true, false);
		Shape shape = builder.insertImage(image);
		shape.setWidth(cell.getCellFormat().getWidth());
		shape.setHeight(cell.getParentRow().getRowFormat().getHeight());
	}
}
